<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/3/8
 * Time: 下午4:07
 */

namespace backend\controllers;

use backend\models\CouponSearch;
use common\models\Coupon;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii;

class CouponController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $searchModel = new CouponSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->get());
        return $this->render('index', ['model' => $searchModel, 'dataProvider' => $dataProvider]);
    }

    public function actionCreate()
    {
        $model = new Coupon();
        if ($model->load(Yii::$app->request->post()) && $model->setExpireAt() && $model->save()) {
            Yii::$app->session->addFlash('success', '创建成功');
            return $this->redirect(['index']);
        }
        return $this->render('create', ['model' => $model]);
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())  && $model->save()) {
            Yii::$app->session->addFlash('success', '更新成功');
            return $this->redirect(['index']);
        }
        return $this->render('create', ['model' => $model]);
    }

    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        if ($model->delete()) {
            Yii::$app->session->addFlash('success', '删除成功');
            return $this->redirect(['index']);
        }
    }

    public function findModel($id)
    {
        $model = Coupon::findOne($id);
        if ($model !== null) {
            return $model;
        }
        throw new NotFoundHttpException("资源不存在");
    }
    public function actionSync(){
        $database = Yii::$app->mongo->getDatabase();
        $coupon_collection = $database->getCollection("coupon")->find();
        foreach($coupon_collection as $item){
            $model = Coupon::findOne(['id'=>$item['id']]);
            if(!empty($model)){

                $model->status=$item['status'];
                $model->save();
            }

        }
        return $this->redirect(['index']);
    }
}
